const { ali_oss } = require('../../server_config.json')
const { MathCode } = require('../libs/common');
const { Add, Query, DelById, QueryOne, Exec, Update, ExecGetOne, Exec_Count } = require('../db/dbhelper');
const logger = require('../libs/log').logger;
var { init, format } = require('../models/ossfile');
var { getfilePath } = require('../libs/file');
var { ali_put, ali_get, ali_signature, ali_del } = require('../libs/ali_oss');
var { ImageRecognition, CheckIdCardInformation } = require('../libs/tencent_cloud');

// 上传
const put_local = async function (doc) {
  try {
    let { name, filepath, pcode } = doc;
    let objectname = MathCode() + name.substring(name.lastIndexOf("."));

    const result = await ali_put(objectname, filepath);
    if (result && result.res && result.res.status == 200) {
      let file_url = `https://${ali_oss.bucket}.${ali_oss.region}.aliyuncs.com/${ali_oss.filepathname}/${objectname}`;
      let ossfileObj = {
        pcode: pcode,
        type: '二维码',
        filename: name,
        objectname: objectname,
        url: file_url,
        ossrequestid: result.res.headers ? result.res.headers['x-oss-request-id'] : '',
        createtime: new Date(),
        updatetime: new Date()
      };
      await Add('hzz_ossfiles', ossfileObj);
      return {
        code: 0,
        data: {
          "url": file_url,// 文件下载地址
          "objectname": objectname,
          "name": name,// 文件名
        },
        msg: '上传成功'
      }
    } else {
      return {
        code: 1,
        data: {
          "url": null,// 文件下载地址
          "name": name,// 文件名
        },
        msg: '上传失败'
      }
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}
// 上传
const test_face = async function () {
  try {
    const ROOT_PATH = process.cwd();
    let file = {
      path: ROOT_PATH + '/files/idcard.jpg',
      name: 'idcard.jpg'
    };
    let objectname = MathCode()  + name.substring(name.lastIndexOf("."));

    const result = await ali_put(objectname, file.path);
    if (result && result.res && result.res.status == 200) {
      let file_url = `https://${ali_oss.bucket}.${ali_oss.region}.aliyuncs.com/${ali_oss.filepathname}/${objectname}${ali_oss.watermark}`;
      let ossfileObj = {
        pcode: '290464549598',
        type: '身份证',
        filename: file.name,
        objectname: objectname,
        contenttype: file['Content-Type'],
        size: file.size,
        url: file_url,
        ossrequestid: result.res.headers ? result.res.headers['x-oss-request-id'] : '',
        createtime: new Date(),
        updatetime: new Date()
      };
      await Add('hzz_ossfiles', ossfileObj);
      return {
        code: 0,
        data: {
          "url": result.url,// 文件下载地址
          "objectname": objectname,
          "name": file.name,// 文件名
        },
        msg: '上传成功'
      }
    } else {
      return {
        code: 1,
        data: {
          "url": result.url,// 文件下载地址
          "name": file.name,// 文件名
        },
        msg: '上传失败'
      }
    }
  } catch (error) {
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}

// 上传
const put = async function (req) {
  try {
    let { pcode, type } = req.body;
    if (!pcode) {
      return {
        code: 1,
        msg: '请先获取用户信息'
      };
    }
    let files = getfilePath(req);
    if (files && files.length) {
      for (let i = 0; i < files.length; i++) {
        let file = files[i];
        let objectname = MathCode() + file.ext;

        const result = await ali_put(objectname, file.path);
        if (result && result.res && result.res.status == 200) {
          let file_url = `https://${ali_oss.bucket}.${ali_oss.region}.aliyuncs.com/${ali_oss.filepathname}/${objectname}${ali_oss.watermark}`;
          let ossfileObj = {
            pcode: pcode,
            type: type,
            filename: file.filename,
            objectname: objectname,
            contenttype: file.mimetype,
            size: file.size + '',
            url: file_url,
            ossrequestid: result.res.headers ? result.res.headers['x-oss-request-id'] : '',
            createtime: new Date(),
            updatetime: new Date()
          };
          await Add('hzz_ossfiles', ossfileObj);
          if (type == '个人相册') {
            // 更新用户头像为相册第一张图
            ossfileUpdatePeopleHead(pcode);
          }
          return {
            code: 0,
            data: {
              "url": result.url,// 文件下载地址
              "name": file.filename,// 文件名
              "objectname": objectname,// 阿里云文件名
            },
            msg: '上传成功'
          };
        } else {
          return {
            code: 1,
            msg: '图片上传失败'
          }
        }
      }
    } else {
      return {
        code: 1,
        msg: '请选择图片上传'
      }
    }
  } catch (error) {
    logger.error('-----ossfile-----------put-------------------error:', error);
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}
// 上传
const put_single = async function (req) {
  try {
    let files = getfilePath(req);
    if (files && files.length) {
      for (let i = 0; i < files.length; i++) {
        let file = files[i];
        let objectname = MathCode() + file.ext;

        const result = await ali_put(objectname, file.path);
        if (result && result.res && result.res.status == 200) {
          let file_url = `https://${ali_oss.bucket}.${ali_oss.region}.aliyuncs.com/${ali_oss.filepathname}/${objectname}${ali_oss.watermark}`;
          let ossfileObj = {
            filename: file.filename,
            objectname: objectname,
            contenttype: file.mimetype,
            size: file.size + '',
            url: file_url,
            ossrequestid: result.res.headers ? result.res.headers['x-oss-request-id'] : '',
            createtime: new Date(),
            updatetime: new Date()
          };
          await Add('hzz_ossfiles', ossfileObj);
         
          return {
            code: 0,
            data: {
              "url": result.url,// 文件下载地址
              "name": file.filename,// 文件名
              "objectname": objectname,// 阿里云文件名
            },
            msg: '上传成功'
          };
        } else {
          return {
            code: 1,
            msg: '上传失败'
          }
        }
      }
    } else {
      return {
        code: 1,
        msg: '请选择文件上传'
      }
    }
  } catch (error) {
    logger.error('-----ossfile-----------put-------------------error:', error);
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}

const fileUpload = async function (req) {
  try {
    let files = getfilePath(req);
    if (files && files.length) {
      let file = files[0];
      let objectname = MathCode() + file.ext;

      const result = await ali_put(objectname, file.path);
      if (result && result.res && result.res.status == 200) {
        return {
          code: 0,
          msg: '上传成功',
          data: result.url
        }
      } else {
        return {
          code: 1,
          msg: '上传失败，请重试'
        }
      }
    } else {
      return {
        code: 1,
        msg: '请选择文件上传'
      }
    }
  } catch (error) {
    return {
      code: 1,
      msg: '上传异常，请重试'
    }
  }
}

// 上传-批量
const putMult = async function (req) {
  try {
    if (req.files && req.files.length) {
      if (req.files.length > 100) {
        return {
          code: 1,
          msg: '请一次选择不超过100个文件上传'
        }
      }
      let files = getfilePath(req);
      let list = [];
      for (let i = 0; i < files.length; i++) {
        let file = files[i];
        // let filename = file.filename;
        // let phone = filename.split('.')[0].split('-')[0];
        // let peoData = await ExecGetOne(`select * from hzz_peoples where phone ='${phone}'`);
        // if(!peoData){
        //  continue;
        // }
        let objectname = MathCode() + file.ext;
        const result = await ali_put(objectname, file.path);
        if (result && result.res && result.res.status == 200) {
          let file_url = `https://${ali_oss.bucket}.${ali_oss.region}.aliyuncs.com/${ali_oss.filepathname}/${objectname+ali_oss.watermark}`;
          let ossfileObj = {
            type: '个人相册',
            // pcode: peoData.code,
            filename: file.filename,
            objectname: objectname,
            contenttype: file.mimetype,
            size: file.size + '',
            url: file_url,
            ossrequestid: result.res.headers ? result.res.headers['x-oss-request-id'] : '',
            createtime: new Date(),
            updatetime: new Date()
          };
          await Add('hzz_ossfiles', ossfileObj);
          // await Exec(`update hzz_peoples set avator = '${file_url}' where code='${peoData.code}'`);
          list.push({
            "url": result.url,// 文件下载地址
            "name": file.filename,// 文件名
            "objectname": objectname,// 阿里云文件名
          });
        } else {
          return {
            code: 1,
            msg: '图片上传失败'
          }
        }
      }
      return {
        code: 0,
        data: list,
        msg: '上传成功'
      }
    } else {
      return {
        code: 1,
        msg: '请选择图片上传'
      }
    }
  } catch (error) {
    logger.error('-----ossfile-----------put-------------------error:', error);
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}

// 下载
const getImgURL = async function (doc) {
  try {
    if (!doc.objectname) {
      return {
        code: 1,
        msg: 'objectname参数未传值'
      };
    }
    let ossfileData = await QueryOne('hzz_ossfiles', { objectname: doc.objectname });
    if (!ossfileData) {
      return {
        code: 1,
        msg: '未找到文件'
      };
    }
    const imgurl = await ali_signature(doc.objectname);
    logger.info('-----ossfile-----------getImgURL-------------------imgurl:', imgurl);
    return {
      code: 0,
      data: imgurl
    }
  } catch (error) {
    logger.info('-----ossfile-----------getImgURL-------------------error:', error);
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}
// 身份认证
const authface_api = async function (doc) {
  try {
    let { idcard, name, objectname } = doc;
    const result = await ali_get(objectname);
    if (result && result.res && result.res.status == 200) {
      let buffer = result.content;
      let base64 = buffer.toString('base64');
      var imagePrefix = "data:image/jpg;base64,";
      base64 = imagePrefix + base64;
      let rdata = await authface_wechat({
        idcard: idcard,
        name: name,
        imgbase64: base64
      });
      if (!rdata || rdata.code) {
        return {
          code: 1,
          msg: '认证异常,请联系客服'
        }
      } else {
        logger.info('-------authface_api----rdata', rdata)
        if (rdata.data.Result == 'Success' || rdata.data.Sim >= 70) {
          // 更新用户信息，姓名、性别、生日、星座
          // if (rdata.data.Name == name) {
            return {
              code: 0,
              data: rdata.data,
              msg: rdata.data.Description || '身份认证成功'
            }
          // } else {
          //   return {
          //     code: 1,
          //     msg: "姓名和证件不匹配"
          //   }
          // }
        } else {
          return {
            code: 1,
            msg: "请检查姓名和证件照是否匹配"//rdata.data.Description
          }
        }
      }
    } else {
      return {
        code: 1,
        msg: '身份识别失败,请重试'
      }
    }
  } catch (error) {
    logger.error("-----------authface_api-------------------error------", error)
    return {
      code: 1,
      msg: '身份识别失败,请重试'
    }
  }
}

// 身份认证
const authface_wechat = async function (doc) {
  try {
    logger.info("-----------authface_wechat-------------------doc------", doc)
    let params = {
      "IdCard": doc.idcard,
      "Name": doc.name,
      "ImageBase64": doc.imgbase64
    };
    let params2 = {
      "ImageBase64": doc.imgbase64
    };
    let rdata = await ImageRecognition(params);
    logger.info("-----------authface_wechat-------------------rdata------", rdata)
    // let rdata = await CheckIdCardInformation(params2);
    return {
      code: 0,
      data: rdata
    }
  } catch (error) {
    logger.error("-----------authface_wechat-------------------error------", error)
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}

// 删除
const del = async function (doc) {
  try {
    logger.info('-------file-------del-------------------', doc)
    if (!doc.objectname) {
      return {
        code: 1,
        msg: 'objectname参数未传值'
      };
    }
    let ossfileData = await QueryOne('hzz_ossfiles', { objectname: doc.objectname });
    if (!ossfileData) {
      return {
        code: 1,
        msg: '未找到文件'
      };
    }
    if (ossfileData.type == '个人相册') {
      let myoss = await Exec_Count('hzz_ossfiles', { pcode: ossfileData.pcode, type: '个人相册' });
      if (myoss == 1) {
        return {
          code: 1,
          msg: '至少保留一张照片'
        };
      }
    }

    await ali_del(doc.objectname);
    await DelById('hzz_ossfiles', ossfileData.id);
    // 更新用户头像为相册第一张图
    ossfileUpdatePeopleHead(ossfileData.pcode);
    return {
      code: 0,
      data: '删除成功'
    }
  } catch (error) {
    logger.info('----hzz_ossfiles---del---------------error:', error);
    return {
      code: 1,
      msg: error ? error.message : ''
    }
  }
}

//列表
const ossfileList = function (doc) {
  return Query('hzz_ossfiles', doc);
}

// 更新pcode
const ossfileUpdatePcode = async function (pcode, filename) {
  let select_sql = `SELECT * FROM hzz_ossfiles  WHERE filename like '${filename}%' AND pcode is null `;
  let list = await Exec(select_sql);
  if (list && list.length) {
    for (let i = 0; i < list.length; i++) {
      const item = list[i];
      let updateOBJ = {
        id: item.id,
        pcode: pcode
      };
      await Update('hzz_ossfiles', format(updateOBJ));
      ossfileUpdatePeopleHead(pcode);
    }
  }
}

// 更新用户头像为相册第一张
const ossfileUpdatePeopleHead = async function (pcode) {
  try {
    let file = await ExecGetOne(`SELECT url FROM hzz_ossfiles WHERE PCODE = '${pcode}' AND type='个人相册' ORDER BY id ASC`);
    logger.info('更新用户头像为相册第一张--file,',file)
    if (file && file.url) {
      let urlList = file.url.split('?');
      let headurl = urlList[0];// + ali_oss.watermark;
      Exec(`update hzz_peoples set avator = '${headurl}' where code='${pcode}'`);
    }
  } catch (error) {
    logger.error('更新用户头像为相册第一张--error,',error)
  }
}
// 初始化用户头像
const initimg = async function () {
  try {
    let list = await Exec('SELECT code,id from hzz_peoples');
    for (let index = 0; index < list.length; index++) {
      const peo = list[index];
      await ossfileUpdatePeopleHead(peo.code);
    }
    return {
      code: 0,
      msg: '初始化用户头像成功'
    }
  } catch (error) {
    return {
      code: 1,
      msg: '初始化用户头像失败' + error ? JSON.stringify(error.stock) : ''
    }
  }
}
// 批量处理水印
const initWaterMark = async function () {
  // let list = await Exec(`select * from hzz_ossfiles`);
  // for (const item of list) {
  //   if (item.url) {
  //     let li = item.url.split('?');
  //     await Exec(`UPDATE hzz_ossfiles SET URL='${li[0] + ali_oss.watermark}' WHERE ID= ${item.id}`);
  //   }
  // }

  let list2 = await Exec(`select id,avator from hzz_peoples where avator!='https://redspider.oss-cn-shenzhen.aliyuncs.com/setting/female_a.png'`);
  for (const item of list2) {
    if (item.avator) {
      let li = item.avator.split('?');
      await Exec(`UPDATE hzz_peoples SET avator='${li[0]}' WHERE ID= ${item.id}`);
    }
  }
  return 'ok';
}

module.exports = {
  ossfileList,
  fileUpload,
  put,
  put_single,
  putMult,
  getImgURL,
  del,
  test_face,
  authface_api,
  put_local,
  ossfileUpdatePcode,
  initimg,
  initWaterMark
}